/*
 * @Author: ls
 * @Date: 2021-10-14 14:00:19
 * @LastEditTime: 2021-10-14 15:15:26
 * @LastEditors: Please set LastEditors
 * @Description: 子弹基类
 * @FilePath: \Alive-master\assets\script\game\bullet\bulletBase.ts
 */

import BulletFactory, { BulletType } from '../bullet/bulletFactory';

const { ccclass, property } = cc._decorator;

@ccclass
export class BulletBase extends cc.Component {
	/** 移动方向 */
	private _moveDir: cc.Vec2 = cc.Vec2.ZERO;
	get moveDir(): cc.Vec2 {
		return this._moveDir;
	}
	set moveDir(dir: cc.Vec2) {
		this._moveDir.x = dir.x;
		this._moveDir.y = dir.y;
	}

	/** 移动速度 */
	private _moveSpeed: number = 0;
	get moveSpeed(): number {
		return this._moveSpeed;
	}
	set moveSpeed(speed: number) {
		if (speed < 0) return;
		this._moveSpeed = speed;
	}

	/** 子弹类型标签 */
	private _tag: BulletType | undefined = undefined;

	/** 子弹工厂 */
	private _bulletFactory: BulletFactory | undefined = undefined;

	/**
	 * 从节点池取出子弹
	 * @param bulletFactory 子弹工厂
	 * @param dir 方向
	 * @param speed 速度
	 * @param tag 标签
	 */
	public reuse(bulletFactory: BulletFactory, dir: cc.Vec2, speed: number, tag: BulletType): void {
		this._bulletFactory = bulletFactory;
		this._tag = tag;

		this.moveSpeed = speed;
		this.moveDir = dir;
	}

	/**
	 * 把子弹回收到节点池
	 */
	public unuse(): void {
		// Util.log('回收成功')
	}

	/** 碰撞后回调 */
	onCollisionEnter(other: cc.Collider, self: cc.Collider): void {
		// Util.log('碰撞')
	}

	update(dt: number): void {
		if (this.moveSpeed === 0) return;

		if (this.moveDir.x !== 0) {
			this.node.x += this.moveDir.x * this.moveSpeed * dt;
		}

		if (this.moveDir.y !== 0) {
			this.node.y += this.moveDir.y * this.moveSpeed * dt;
		}

		if (Math.abs(this.node.x) > cc.winSize.width / 2 || Math.abs(this.node.y) > cc.winSize.height / 2) {
			// Util.log('边界回收')
			this._bulletFactory.bulletPools[this._tag].put(this.node);
		}
	}
}
